#!/bin/bash
#
#    am-tint2restart: a script to restart all tint2 instances
#    Copyright (C) 2015 damo    <damo@bunsenlabs.org>
#    Copyright (C) 2015-2016  John Crawley <john@bunsenlabs.org>
#    Borrowed with love by arcolinux.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

HELP='    am-tint2-restart a script to restart all running instances of tint2

Options:
    -h --help   show this message

No other options are supported.
'
# look for a help option somewhere
for i in "$@"
do
    case "$i" in
    -h|--help)
        echo "$HELP"
        exit 0
        ;;
    esac
done

pidof tint2 >/dev/null || {
    echo "$0: no tint2 processes found" >&2
    exit 1
}

declare -A commands # associative array

while read pid cmd; do
    if [[ ${cmd%% *} = tint2 ]]; then
        kill "$pid"
        commands[$cmd]=1 # duplicate commands will be launched only once
    fi
done <<< "$(pgrep -a tint2)"

sleep 1

# any processes still running will be killed with SIGKILL
while read pid cmd; do
    if [[ ${cmd%% *} = tint2 ]]; then
        kill -KILL "$pid"
        commands[$cmd]=1
    fi
done <<< "$(pgrep -a tint2)"

sleep 1
for i in "${!commands[@]}" # go through the indexes
do
    (setsid $i &)
    sleep 0.1
done

#sleep 1
#am-compositor --restart  # restart compositor

exit 0
